<template>
  <div>
    <!-- 筛选区域 -->
    <el-card>
      <el-input class="select-box" size="large" placeholder="请输入角色名称" v-model="roleName" />
      <el-button type="primary" :icon="Search" @click="selectList"> 查询 </el-button>
      <el-button @click="resetInput">清空</el-button>
    </el-card>

    <!-- 角色列表 -->
    <el-card class="box-card">
      <div>
        <el-button type="primary" @click="addRoleBtn">添加</el-button>
      </div>

      <el-table :data="roleList" border stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="88" />
        <el-table-column prop="roleName" label="角色管理" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              size="small"
              type="info"
              :icon="InfoFilled"
              :title="'分配权限'"
              @click="toSetRole(row)"
            />
            <el-button size="small" type="warning" :icon="Edit" @click="editRole(row)" />
            <el-button size="small" type="danger" :icon="Delete" @click="removeRole(row)" />
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="page"
        v-model:page-size="limit"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增角色弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑弹框' : '新增弹框'"
      width="30%"
      align-center
      :before-close="handleClose"
    >
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="ruleFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Search, InfoFilled, Edit, Delete } from '@element-plus/icons-vue'
import { reqDelRole, reqRoleList, reqSaveRole, reqUpdateRole } from '@/api/role'
import type { IRoleItem } from '@/types/role'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'

const router = useRouter()

// 需要筛选的角色名称
const roleName = ref('')
// 权限管理列表数据
const roleList = ref<IRoleItem[]>([])

// 分页数据
const page = ref(1)
const limit = ref(5)
const total = ref(0)

// 是否展示新增、编辑角色弹框
const dialogVisible = ref(false)
const ruleFormRef = ref<FormInstance>()

// 新增角色表单数据
const ruleForm = ref({} as IRoleItem)
// 新增角色表单验证
const ruleFormRules = reactive<FormRules>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 10, message: '角色名称在在 1 ~ 10 个字之间', trigger: 'blur' }
  ]
})

// 是否是编辑
const isEdit = ref(false)

// 删除
const removeRole = (row: IRoleItem) => {
  ElMessageBox.confirm('确认删除该角色?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await reqDelRole(row.id as number)
      ElMessage({
        type: 'success',
        message: '商品删除成功'
      })
      getRoleList()
    })
    .catch(() => {
      ElMessage.info('商品删除失败')
    })
}

// 新增编辑按钮
const addRoleBtn = () => {
  dialogVisible.value = true
  isEdit.value = false
}

// 分配权限
const toSetRole = (row: IRoleItem) => {
  router.push({
    path: '/acl/role/auth',
    query: {
      id: row.id,
      roleName: row.roleName
    }
  })
}

// 点击编辑按钮
const editRole = (row: IRoleItem) => {
  // 展示弹框
  dialogVisible.value = true
  // 编辑操作
  isEdit.value = true

  // 将当前行的数据赋值给表单数据
  nextTick(() => {
    ruleForm.value = { ...row }
  })
}

// 关掉弹框
const handleClose = () => {
  // 隐藏弹框
  dialogVisible.value = false

  // 清空表单数据和样式
  ruleFormRef.value?.resetFields()

  // 重置数据
  ruleForm.value = {} as IRoleItem

  // 重置新增、编辑状态
  isEdit.value = false
}

// 新增、编辑确认弹框
const confirm = async () => {
  // 兜底验证
  await ruleFormRef.value?.validate(async (valid) => {
    if (!valid) return

    const res = isEdit.value
      ? await reqUpdateRole(ruleForm.value)
      : await reqSaveRole(ruleForm.value)

    if (res.code === 20000) {
      // 清空表单数据和样式、隐藏弹框
      handleClose()
      // 获取角色列表数据
      getRoleList()
      // 给用户进行提示
      ElMessage.success(isEdit.value ? '编辑角色成功' : '新增角色成功')
    }
  })
}

// 筛选角色
const selectList = () => {
  if (roleName.value.trim() === '') return
  getRoleList()
}

// 清空输入框
const resetInput = () => {
  roleName.value = ''
  getRoleList()
}

onMounted(() => {
  getRoleList()
})

// 获取角色管理列表
const getRoleList = async () => {
  const res = await reqRoleList(page.value, limit.value, roleName.value)

  if (res.code === 20000) {
    roleList.value = res.data.items
    total.value = res.data.total
  }
}

// page-size 改变时触发
const handleSizeChange = (val: number) => {
  limit.value = val
  getRoleList()
}

// current-page 改变时触发
const handleCurrentChange = (val: number) => {
  page.value = val
  getRoleList()
}
</script>

<script lang="ts">
export default {
  name: 'RoleList'
}
</script>

<style lang="scss" scoped>
.select-box {
  width: 200px;
  height: 34px;
  margin-right: 16px;
}

.box-card {
  margin-top: 14px;

  .el-table {
    margin-top: 18px;
  }

  .el-pagination {
    margin-top: 18px;
    display: flex;
    justify-content: center;
  }
}
</style>
